<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

// 响应式数据
const activeTab = ref('month')
const now = new Date()
const formatDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

const queryForm = ref({
  startDate: formatDate(new Date(now.getFullYear(), now.getMonth(), 1)), // 默认本月第一天
  endDate: formatDate(now) // 默认今天
})

const chartData = ref({
  categories: [],
  values: []
})

const tableData = ref([])

// 自定义进度条颜色
const customColors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: '#6f7ad3', percentage: 100 }
]

// 设置日期范围的方法
const setDateRange = () => {
  const today = new Date()
  const year = today.getFullYear()
  const month = today.getMonth()

  switch (activeTab.value) {
    case 'month':
      // 本月
      queryForm.value.startDate = formatDate(new Date(year, month, 1))
      queryForm.value.endDate = formatDate(today)
      break
    case 'quarter':
      // 本季度
      const quarter = Math.floor(month / 3)
      const quarterStartMonth = quarter * 3
      queryForm.value.startDate = formatDate(new Date(year, quarterStartMonth, 1))
      queryForm.value.endDate = formatDate(today)
      break
    case 'year':
      // 本年
      queryForm.value.startDate = formatDate(new Date(year, 0, 1))
      queryForm.value.endDate = formatDate(today)
      break
  }
}

// 获取类目名称
const getAllCategory = () => {
  return axios.get(`/category/getCategoryName`).then(resp => {
    chartData.value.categories = resp.data
  })
}

// 获取销量数据
const getAllCount = () => {
  return axios.post(`/category/getCount`, queryForm.value).then(resp => {
    chartData.value.values = resp.data
    initChart() // 数据更新后重新渲染图表
  })
}

// 初始化图表
const initChart = () => {
  const chartDom = document.getElementById('chart-container')
  if (!chartDom) return

  // 先销毁之前的图表实例
  const existingChart = echarts.getInstanceByDom(chartDom)
  if (existingChart) {
    existingChart.dispose()
  }

  const myChart = echarts.init(chartDom)

  const option = {
    title: {
      text: '各类目销量',
      left: 'center',
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: chartData.value.categories,
      axisLabel: {
        interval: 0,
        rotate: 45
      },
      axisLine: {
        lineStyle: {
          color: '#DCDFE6'
        }
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#DCDFE6'
        }
      },
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [{
      name: '销量',
      type: 'bar',
      data: chartData.value.values,
      barMinHeight: 1,
      itemStyle: {
        color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
          { offset: 0, color: '#83bff6' },
          { offset: 0.5, color: '#188df0' },
          { offset: 1, color: '#0076e3' }
        ]),
        borderRadius: [4, 4, 0, 0]
      },
      emphasis: {
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: '#2378f7' },
            { offset: 0.7, color: '#2378f7' },
            { offset: 1, color: '#83bff6' }
          ])
        }
      }
    }]
  }

  myChart.setOption(option)

  window.addEventListener('resize', () => {
    myChart.resize()
  })
}

// 获取表格统计数据（默认本月）
const categoryCount = () => {
  const now = new Date()
  const currentYear = now.getFullYear()
  const currentMonth = (now.getMonth() + 1).toString().padStart(2, '0')
  const currentYearMonth = `${currentYear}-${currentMonth}`

  axios.get(`/category/categoryCount/${currentYearMonth}`).then(resp => {
    // 处理数据：转换为百分数
    tableData.value = resp.data.map(item => {
      const monthChangeKey = Object.keys(item.monthChange)[0] || '0.00'
      const amountChangeKey = Object.keys(item.amountChange)[0] || '0.00'

      return {
        ...item,
        salesRatio: (parseFloat(item.salesRatio) * 100).toFixed(2),
        amountRatio: (parseFloat(item.amountRatio) * 100).toFixed(2),
        monthChange: {
          [(parseFloat(monthChangeKey) * 100).toFixed(2)]: item.monthChange[monthChangeKey]
        },
        amountChange: {
          [(parseFloat(amountChangeKey) * 100).toFixed(2)]: item.amountChange[amountChangeKey]
        }
      }
    })
  })
}

// 监听activeTab的变化
watch(activeTab, (newVal) => {
  setDateRange()
  getAllCount()
})

// 页面挂载后加载数据并初始化图表
onMounted(() => {
  getAllCategory().then(() => {
    getAllCount().then(() => {
      initChart()
    })
  })
  categoryCount()
})
</script>

<template>
  <div class="product-statistics">
    <h2 class="page-title">商品统计</h2>
    <el-card class="statistics-card">
      <div slot="header" class="card-header">
        <span class="header-title">各类目交易情况</span>
      </div>
      <div class="statistics-content">
        <div class="filter-container">
          <el-tabs v-model="activeTab" class="statistics-tabs">
            <el-tab-pane label="本月" name="month"></el-tab-pane>
            <el-tab-pane label="本季度" name="quarter"></el-tab-pane>
            <el-tab-pane label="本年" name="year"></el-tab-pane>
          </el-tabs>
          <el-form-item class="date-range-form-item">
            <div class="date-range-container">
              <el-date-picker
                  v-model="queryForm.startDate"
                  type="date"
                  placeholder="开始日期"
                  value-format="YYYY-MM-DD"
                  class="compact-date-picker"
                  popper-class="date-picker-popper"
              />
              <span class="date-range-separator">至</span>
              <el-date-picker
                  v-model="queryForm.endDate"
                  type="date"
                  placeholder="结束日期"
                  value-format="YYYY-MM-DD"
                  class="compact-date-picker"
                  popper-class="date-picker-popper"
              />
            </div>
          </el-form-item>
        </div>
      </div>
      <div id="chart-container" style="width: 100%; height: 400px; margin-top: 20px"></div>

      <!-- 统计表格 -->
      <div class="table-container">
        <el-table
            :data="tableData"
            style="width: 100%; margin-top: 30px"
            border
            stripe
            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'bold' }"
            class="statistics-table"
            :cell-style="{ padding: '12px 0' }"
        >
          <el-table-column
              prop="category"
              label="商品类目"
              width="150"
              align="center"
              fixed
              header-align="center"
          />
          <el-table-column label="销售数量" align="center" header-align="center">
            <el-table-column
                prop="salesCount"
                label="数量"
                width="150"
                align="center"
                sortable
            />
            <el-table-column
                prop="salesRatio"
                label="销量占比"
                width="180"
                align="center"
            >
              <template #default="{ row }">
                <div class="progress-container">
                  <el-progress
                      :percentage="parseFloat(row.salesRatio)"
                      :stroke-width="14"
                      :show-text="false"
                      :color="customColors"
                      class="ratio-progress"
                  />
                  <span class="ratio-text">{{ row.salesRatio }}%</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                prop="monthChange"
                label="环比变化"
                width="150"
                align="center"
            >
              <template #default="{ row }">
                <div class="trend-cell">
                  <i v-if="Object.keys(row.monthChange)[0] === '0.00'" class="el-icon-right" style="color: #909399"></i>
                  <i v-else :class="['trend-icon', row.monthChange[Object.keys(row.monthChange)[0]] === 'up' ? 'el-icon-top' : 'el-icon-bottom']"
                     :style="{ color: row.monthChange[Object.keys(row.monthChange)[0]] === 'up' ? '#f56c6c' : '#67c23a' }"></i>
                  <span :style="{
                    color: Object.keys(row.monthChange)[0] === '0.00' ? '#909399' :
                           row.monthChange[Object.keys(row.monthChange)[0]] === 'up' ? '#f56c6c' : '#67c23a'
                  }">
                    {{ Object.keys(row.monthChange)[0] === '0.00' ? '持平' : Object.keys(row.monthChange)[0] + '%' }}
                  </span>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
          <el-table-column label="销售金额" align="center" header-align="center">
            <el-table-column
                prop="salesAmount"
                label="金额"
                width="180"
                align="center"
                sortable
            />
            <el-table-column
                prop="amountRatio"
                label="销售额占比"
                width="180"
                align="center"
            >
              <template #default="{ row }">
                <div class="progress-container">
                  <el-progress
                      :percentage="parseFloat(row.amountRatio)"
                      :stroke-width="14"
                      :show-text="false"
                      :color="customColors"
                      class="ratio-progress"
                  />
                  <span class="ratio-text">{{ row.amountRatio }}%</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column
                prop="amountChange"
                label="环比变化"
                width="150"
                align="center"
            >
              <template #default="{ row }">
                <div class="trend-cell">
                  <i v-if="Object.keys(row.amountChange)[0] === '0.00'" class="el-icon-right" style="color: #909399"></i>
                  <i v-else :class="['trend-icon', row.amountChange[Object.keys(row.amountChange)[0]] === 'up' ? 'el-icon-top' : 'el-icon-bottom']"
                     :style="{ color: row.amountChange[Object.keys(row.amountChange)[0]] === 'up' ? '#f56c6c' : '#67c23a' }"></i>
                  <span :style="{
                    color: Object.keys(row.amountChange)[0] === '0.00' ? '#909399' :
                           row.amountChange[Object.keys(row.amountChange)[0]] === 'up' ? '#f56c6c' : '#67c23a'
                  }">
                    {{ Object.keys(row.amountChange)[0] === '0.00' ? '持平' : Object.keys(row.amountChange)[0] + '%' }}
                  </span>
                </div>
              </template>
            </el-table-column>
          </el-table-column>
        </el-table>
      </div>
    </el-card>
  </div>
</template>

<style scoped>
.product-statistics {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

.page-title {
  font-size: 22px;
  color: #303133;
  margin-bottom: 20px;
  font-weight: 600;
}

.statistics-card {
  margin-top: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  min-height: calc(100vh - 100px);
  display: flex;
  flex-direction: column;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.header-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
}

.statistics-content {
  margin-bottom: 20px;
}

.filter-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-wrap: wrap;
  gap: 16px;
  width: 100%;
}

.statistics-tabs {
  flex: 1;
  min-width: 200px;
}

/* 日期范围容器 */
.date-range-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 紧凑型日期选择器 */
.compact-date-picker {
  width: 160px;
}

/* 日期分隔符 */
.date-range-separator {
  color: #606266;
  font-size: 14px;
  padding: 0 4px;
}

/* 表单项调整 */
.date-range-form-item {
  margin-bottom: 0;
}

.table-container {
  margin-top: 30px;
  flex: 1;
  display: flex;
  flex-direction: column;
}

.statistics-table {
  border-radius: 8px;
  overflow: hidden;
  flex: 1;
}

.statistics-table::before {
  display: none;
}

.trend-cell {
  display: flex;
  align-items: center;
  justify-content: center;
}

.trend-icon {
  margin-right: 4px;
  font-size: 14px;
}

.progress-container {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.ratio-progress {
  flex: 1;
  max-width: 100px;
  margin-right: 10px;
}

.ratio-text {
  width: 50px;
  text-align: left;
}

/* 响应式调整 */
@media (max-width: 992px) {
  .filter-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .date-range-container {
    width: 100%;
  }

  .compact-date-picker {
    width: calc(50% - 20px);
  }

  .statistics-table {
    font-size: 14px;
  }

  .progress-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .ratio-progress {
    width: 100%;
    margin-right: 0;
    margin-bottom: 5px;
  }

  .ratio-text {
    width: auto;
  }
}
</style>

<style>
/* 全局样式调整 */
.date-picker-popper {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
}

.statistics-table .el-table__header-wrapper th {
  font-weight: 600;
}

.statistics-table .el-table__body tr:hover > td {
  background-color: #f5f7fa !important;
}

.statistics-table .el-table__body td {
  transition: background-color 0.3s;
}

.statistics-table .el-progress-bar {
  padding-right: 0;
  margin-right: 0;
}

.statistics-table .el-table__fixed-right::before {
  display: none;
}
.trend-cell .el-icon-right {
  font-size: 14px;
  margin-right: 4px;
  color: #909399; /* 中性灰色 */
}
</style>